import { Injectable } from '@nestjs/common';
import { CreatePwdManagementDto } from './dto/create-pwd-management.dto';
import { UpdatePwdManagementDto } from './dto/update-pwd-management.dto';
import { Repository, Like } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { PwdManagement } from './entities/pwd-management.entity'

@Injectable()
export class PwdManagementService {
    constructor(@InjectRepository(PwdManagement) private readonly pwdManagement: Repository<PwdManagement>) { }
    create(createPwdManagementDto: CreatePwdManagementDto) {
        const data = new PwdManagement()
        data.account = createPwdManagementDto.account
        data.pwd = createPwdManagementDto.pwd
        data.website = createPwdManagementDto.website
        data.remark = createPwdManagementDto.remark
        return this.pwdManagement.save(data)
    }

    async findAll(query: { keyword: string, pageNo: number, pageSize: number }) {
        const records = await this.pwdManagement.find({
            where: [
                { account: Like(`%${query.keyword}%`) },
                { pwd: Like(`%${query.keyword}%`) },
                { website: Like(`%${query.keyword}%`) },
                { remark: Like(`%${query.keyword}%`) },
            ],
            order: {
                id: "DESC"
            },
            skip: (query.pageNo - 1) * query.pageSize,
            take: query.pageSize,
        })
        const total = await this.pwdManagement.count({
            where: [
                { account: Like(`%${query.keyword}%`) },
                { pwd: Like(`%${query.keyword}%`) },
                { website: Like(`%${query.keyword}%`) },
                { remark: Like(`%${query.keyword}%`) },
            ],
        })
        return {
            records,
            total
        }
    }

    findOne(id: number) {
        return this.pwdManagement.findOneBy({ id })
    }

    update(id: number, updatePwdManagementDto: UpdatePwdManagementDto) {
        return this.pwdManagement.update(id, updatePwdManagementDto)
    }

    remove(id: number) {
        return this.pwdManagement.delete(id)
    }
}
